package com.xuyuan.interview.scene.coupon;

import com.xuyuan.interview.scene.api.CouponCondition;
import com.xuyuan.interview.scene.entity.Order;
import com.xuyuan.interview.scene.entity.Product;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class GiftCoupon extends CouponCondition {
    private List<Product> gifts;

    @Override
    public String getCouponName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public Order applyDiscount(Order order) {
        List<Product> list = order.getGifts();
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
            order.setGifts(list);
        }
        list.addAll(this.gifts);
        return order;
    }

    @Override
    public BigDecimal findPriority(Order order) {
        // return order.getTotalPrice().subtract(order.getGifts().stream().map(Product::getProductPrice).reduce(BigDecimal.ZERO, BigDecimal::add));
        return order.getTotalPrice().subtract(order.getGifts().stream().map(Product::getProductPrice).max(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
    }
}
